# -*- coding: utf-8 -*-

from odoo.http import request

from ..utils.meta import Singleton
from ..utils.exceptions import WechatMiniAppException

from .miniapp import WechatMiniApp
from .mpapp import WechatMPApp


repo = {}


class WechatAppFactory(object, metaclass=Singleton):
    _instance = None

    def __getitem__(self, site):
        if site in repo:
            return repo[site]

        if site is None:
            app_entry = request.env['wechat.miniapp'].sudo().search([
                ('default', '=', True)
            ])
        else:
            app_entry = request.env['wechat.miniapp'].sudo().search([
                ('name', '=', site),
            ])
        if not app_entry:
            raise WechatMiniAppException(
                errcode=201001,
                params={
                    'site': site,
                }
            )
        app_entry = app_entry[0]
        if not app_entry.settings:
            raise WechatMiniAppException(
                errcode=201010,
                params={
                    'site': site,
                }
            )
        settings = app_entry.settings
        if settings.app_type == 0:
            app = WechatMiniApp(site, app_entry)
        elif settings.app_type == 1:
            app = WechatMPApp(site, app_entry)
        else:
            raise WechatMiniAppException(
                errcode=201011,
                params={
                    'site': site,
                }
            )
        repo[site] = app
        return app


class WechatMPFactory(object, metaclass=Singleton):
    _instance = None

    def __getitem__(self, site):
        if site in repo:
            return repo[site]

        if site is None:
            app_entry = request.env['wechat.miniapp'].sudo().search([
                ('default', '=', True)
            ])
        else:
            app_entry = request.env['wechat.miniapp'].sudo().search([
                ('name', '=', site),
            ])
        if not app_entry:
            raise WechatMiniAppException(
                errcode=201001,
                params={
                    'site': site,
                }
            )
        app_entry = app_entry[0]
        for settings in app_entry.settings:
            if settings.app_type != 1:
                raise WechatMiniAppException(
                    errcode=201005,
                    params={
                        'site': site,
                    }
                )
        app = WechatMPApp(site, app_entry)
        repo[site] = app
        return app
